//
//  WmcPhotoPreviewVC.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/4/15.
//

import RxGesture
import UIKit
import YPBedrock
import YPGraphicEngine

// MARK: - 扩展WmcPhotoPreviewVC + WmcNavigatorProtocol

extension WmcPhotoPreviewVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.photoPreview]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        var vm = WmcPhotoPreviewVM()
        if let viewModel = parms.context as? WmcPhotoPreviewVM {
            vm = viewModel
        }
        let vc = WmcPhotoPreviewVC(vm)
        return vc
    }
}

// MARK: - 扩展WmcPhotoPreviewVC + WmcVMProtocol

extension WmcPhotoPreviewVC: WmcVMProtocol {
    typealias VMType = WmcPhotoPreviewVM
}

// MARK: - [WmcPhotoPreviewVC]

class WmcPhotoPreviewVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        // 标题
        titleLabel.attributedText = photoPreviewDelegate?.settingAttributedTitle(.current)

        // 加载图片
        viewModel.loadPreviewImage()
    }

    // Internal

    lazy var titleLabel: UILabel = {
        let label = UILabel.YP.Create(font: 22.yp.uiFont(weight: .bold),
                                      color: UIColor.black,
                                      alignment: .left)
        return label
    }()

    lazy var imagePreview: WmcImageBrowsePreview = {
        let view = WmcImageBrowsePreview()
        return view
    }()
 
    /// 静态二维码视图(用作展示)
    private(set) lazy var staticQRView: WmcQRCodeVerifyView = {
        let view = WmcQRCodeVerifyView()
        return view
    }()
    
    
    /// 动态二维码视图(用于生成照片)
    private(set) lazy var dynamicQRView: WmcQRCodeVerifyView = {
        let view = WmcQRCodeVerifyView()
        return view
    }()

    /// 水印内容视图
    lazy var watermarkContentView: WmcWatermarkContentView = {
        let view = WmcWatermarkContentView()
        view.isLockReverse = false
        return view
    }()

    /// 工具栏
    lazy var footerView: WmcPhotoPreviewFooterView = {
        let view = WmcPhotoPreviewFooterView()
        return view
    }()

    /// 底部视图
    lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()

    /// 水印选择
    lazy var watermarkSelectView: WmcSelectWatermarkPreviewView = {
        let view = WmcSelectWatermarkPreviewView()
        view.styleMode = .staticDraw
        return view
    }()

    /// 代理获取，减少代码长度
    var photoPreviewDelegate: WmcPhotoPreviewDelegate? {
        return YPWmcManager.shared.uiDelegate.photoPreviewDelegate
    }
    
    var qrcodeView: WmcQRCodeVerifyView? {
        return viewModel.showQRCode ? dynamicQRView : nil
    }

    override func backAction() {
        super.backAction()
    }

    // 驱动
    override func bindDriving() {
        // 驱动图片渲染混合
        YPWmcDrivingManager.shared.photoPreview_blendPhotoBlock = { [weak self] in
            guard let self = self else { return }
            self.viewModel.fotoMix(watermarkContentView: self.watermarkContentView, qrcodeView: self.qrcodeView)
        }

        // 驱动保存照片
        YPWmcDrivingManager.shared.photoPreview_savePhotoToLocalAlbumBlock = { [weak self] result in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.saveAlbum(result)
        }
    }

    override func bindViewAction() {
        // 点击重拍
        footerView.retakeBtn.yp.addEvent { _ in
            let alert = WmcAlertView()
            alert.title = "确定重拍吗？"
            alert.msg = "重拍会丢失刚才拍摄的照片"
            alert.style = .confirmCancel
            alert.confirmBlock = { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.popVC() { [weak self] in
                    guard let weakSelf = self else { return }
                    weakSelf.viewModel.retakeBack()
                }
            }
            alert.show()
        }

        // 点击水印选择按钮
        footerView.watermarkBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            // 隐藏相机上水印
            weakSelf.watermarkContentView.isHidden = true
            // 加载水印和静态数据
            let staticData = weakSelf.viewModel.loadWatermarkRelay.value.staticData
            weakSelf.watermarkSelectView.staticData = staticData
            weakSelf.watermarkSelectView.show(selectWatermark: weakSelf.viewModel.loadWatermarkRelay.value)
        }

        // ---水印选择
        watermarkSelectView.didSelectWatermarkBlock = { [weak self] _, wmModel in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.setWatermarkModel(wmModel)
        }

        // ---无水印选择
        watermarkSelectView.didSelectEmptyWatermarkBlock = { [weak self] wmModel in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.setWatermarkModel(wmModel)
        }

        // ---水印编辑
        watermarkSelectView.editWatermarkBlock = { [weak self] wmModel in
            guard let weakSelf = self else { return }
            weakSelf.actionEditWatermark(wmModel)
        }
        // ---水印分享
        watermarkSelectView.shareWatermarkBlock = { wmModel in
            let vm = WmcShareWatermarkVM()
            vm.watermarkModel = wmModel
            WmcNavigatorManager.push(.shareWatermark, parms: vm)
        }
        // ---水印选择即将消失
        watermarkSelectView.willDismissBlock = { [weak self] in
            guard let weakSelf = self else { return }
            // 显示相机上水印
            weakSelf.watermarkContentView.isHidden = false
        }

        // ---水印选择需要消失
        watermarkSelectView.dismissBlock = { [weak self] in
            guard let weakSelf = self else { return }
            // 显示相机上水印
            weakSelf.watermarkContentView.isHidden = false
        }
        
        // 水印加载完成
        watermarkSelectView.watermarkListLoadCompletion = { list in
            YPWmcManager.shared.uiDelegate.homeDelegate?.watermarkListDidLoad(.current, list: list)
        }

        // 水印被点击时候
        watermarkContentView.watermarkActionBlock = { [weak self] view in
            guard let weakSelf = self,
                  let watermarkModel = weakSelf.watermarkContentView.watermarkModel else { return }
            weakSelf.actionEditWatermark(watermarkModel)
        }

        // 点击保存
        footerView.saveBlock = { [weak self] in
            guard let self = self else { return }
//            WmcHudManager.toast("正在保存")
            self.viewModel.fotoMix(watermarkContentView: self.watermarkContentView, qrcodeView: self.qrcodeView)
            if let value = self.viewModel.photoFinishRelay.value {
                self.viewModel.saveAlbum(value)
            }
//            WmcHudManager.toast("保存成功")
            self.popVC(completion: { [weak self] in
                guard let self = self else { return }
                self.viewModel.saveBack()
            })
        }

        // 点击朋友圈
        footerView.friendCircleBtn.yp.addEvent { [weak self] _ in
            guard let self = self else { return }
            self.viewModel.fotoMix(watermarkContentView: self.watermarkContentView, qrcodeView: self.qrcodeView)
            self.viewModel.shareFriendCircle()
        }

        // 点击微信
        footerView.wechatBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.fotoMix(watermarkContentView: weakSelf.watermarkContentView, qrcodeView: weakSelf.qrcodeView)
            weakSelf.viewModel.shareWechat()
        }

        // 水印开始布局
        watermarkContentView.watermarkLayoutBlock = { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.imagePreview.hitTestViews = weakSelf.watermarkContentView.hitsViews
        }

        // 预览图布局完成
        imagePreview.resetSubViewSizeBlock = { [weak self] previewSize in
            guard let weakSelf = self else { return }
            if previewSize.width > previewSize.height { // 横图
                // 水印缩放
                let aspectHeight = weakSelf.viewModel.aspectRatio.aspectHeight
                let scaleX = previewSize.width / aspectHeight
                let scaleY = previewSize.height / Wmc_screenWidth
                weakSelf.watermarkContentView.secondaryTransform = CGAffineTransform(scaleX: scaleX, y: scaleY)
                // 移动点位转换
                if let centerPoint = weakSelf.viewModel.watermarkCenterPoint {
                    let centerXr = centerPoint.x / aspectHeight
                    let centerX = centerXr * previewSize.width
                    let centerYr = centerPoint.y / Wmc_screenWidth
                    let centerY = centerYr * previewSize.height
                    weakSelf.watermarkContentView.moveWatermarkView(.init(x: centerX, y: centerY))
                }
            } else { // 竖图
                if let centerPoint = weakSelf.viewModel.watermarkCenterPoint {
                    weakSelf.watermarkContentView.moveWatermarkView(centerPoint)
                }
            }
        }
    }

    override func bindViewModel() {
        // 图片加载
        viewModel.loadPreviewImageRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self,
                  let image = value else { return }
            weakSelf.imagePreview.configImage(.init(uiImage: image))
        }).disposed(by: rx.disposeBag)

        // 水印编辑状态
        viewModel.watermarkInteractionEnabledRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.watermarkContentView.isHidden = !value
        }).disposed(by: rx.disposeBag)

        // 水印加载
        viewModel.loadWatermarkRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            // 静态渲染
            // 是否需要认证水印
            let showCertification = !WmcPreferenceSettingsManager.shared.cameraSetting.hiddenOfficialMark
            weakSelf.watermarkContentView.setWatermarkModel(value,
                                                            styleMode: .staticDraw,
                                                            showCertification: showCertification)
        }).disposed(by: rx.disposeBag)

        // 画幅比
        viewModel.aspectRatioRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self,
                  let image = weakSelf.viewModel.currentStandardImage else { return }
            var aspectRatio: YPGESunglasses.AspectRatio = value
            if image.size.width > image.size.height {
                aspectRatio = .ar_4_3
            }
            weakSelf.setAspectRatio(aspectRatio)
        }).disposed(by: rx.disposeBag)

        // 图片混合完成
        viewModel.photoFinishRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self,
                  var value = value else { return }
            // 回调外部事务
            weakSelf.photoPreviewDelegate?.photoDisposeComplete(.current,
                                                                photoResult: value)
        }).disposed(by: rx.disposeBag)
    }

    override func makeUI() {
        
        let hMargin = 16.0.wmc_autoHor
        // 导航
        makeNavView(style: .white, showShadow: true)
        navView.backImageView.isHidden = true
        navView.backControl.isHidden = true // 无返回效果

        // 可设置标题
        navView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.bottom.equalTo(navView)
            make.left.equalTo(Wmc_standardEdge.left)
            make.right.equalTo(-Wmc_standardEdge.right)
        }

        addSubview(imagePreview)
        imagePreview.imageView.addSubview(watermarkContentView)
        // 二维码
        if viewModel.showQRCode { // 如果要显示二维码
            let qrcodeW = 60.wmc_autoHor
            let qrcodeH = 80.wmc_autoHor
            // 动态二维码视图
            // 设置控件位置(位于屏幕外面)
            dynamicQRView.frame.origin = CGPoint(x: -10000.0, y: -10000.0)
            addSubview(dynamicQRView)
            // 静态二维码图标
            imagePreview.imageView.addSubview(staticQRView)
            staticQRView.snp.makeConstraints { make in
                make.top.equalTo(hMargin)
                make.right.equalTo(-hMargin)
                make.width.equalTo(qrcodeW)
                make.height.equalTo(qrcodeH)
            }
        }
        addSubview(footerView)
        addSubview(bottomView)
        watermarkContentView.snp.makeConstraints { make in
            make.center.size.equalToSuperview()
        }
    }

    /// 编辑水印
    func actionEditWatermark(_ watermarkModel: WmcWatermarkDetailModel) {
        // 询问代理是否有自定义操作
        if let action = photoPreviewDelegate?.watermarkWillEdit(.current,
                                                                watermarkModel: watermarkModel)
        {
            action.transactionDefaultCase { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.editWatermark(watermarkModel)
            }
        } else {
            editWatermark(watermarkModel)
        }
    }

    /// 编辑水印
    func editWatermark(_ watermarkModel: WmcWatermarkDetailModel) {
        let vm = WmcEditWatermarkVM()
        vm.watermarkModel = watermarkModel
        vm.watermarkStyleMode = .staticEdit // 静态渲染
        WmcNavigatorManager.push(.editWatermark, parms: vm)
        // 当编辑完成后的回调
        vm.editCompleteBlock = { [weak self] wmModel in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.setWatermarkModel(wmModel)
        }
    }
}
